<?php

/**
 * @param emailaddress[]
 * @param id                ;id creater
 */
$m = new MongoClient('mongodb://ftp.giemiebier.nl');
//redbean mysql
require_once('rb.php');
R::setup('mysql:host=ftp.giemiebier.nl:3306;dbname=personify', 'school', 'admin123');

function getUser($email) {
    $user = R::findOne("users", "emailaddress=?", array($email));
    return $user;
}

function getUserById($id) {
    $user = R::findOne("users", "id=?", array($id));
    return $user;
}

$ids = array();
$users = array();
$ids[] = $_POST['id'];
$tmp_user = getUserById($_POST['id']);
$tmp['email'] = $tmp_user->emailaddress;
$tmp['id'] = $tmp_user->ID;
$users[] = $tmp;
$emails = explode(",", $_POST['email']);
foreach ($emails as $email) {
    $user = getUser($email);
    if ($user != null) {
        $ids[] = $user->ID;
        $user_tmp = array();
        $user_tmp['email'] = $user->emailaddress;
        $user_tmp['id'] = $user->ID;
        if(!in_array($user_tmp, $users)){
            $users[] = $user_tmp;
            
        }
        
    }
}
if (count($users) > 1) {
    //select database
    $db = $m->chatdb;
    $id_list = array("users" => $users);
    $chat = $db->chat;
    $chat->insert($id_list);

    foreach ($users as $temp) {

        $user_chats = $db->user_chats;
        $data = array(
            'chat_id' => $id_list["_id"]->{'$id'},
        );
        //var_dump($data);
        $user_chats->update(array("_id" => $temp['id']), array('$push' => $data), array('upsert' => true));
        $data = array(
            'email' => $temp['email']
        );
        $user_chats->update(array("_id" => $temp['id']), array('$addToSet' => $data), array('upsert' => true));
        
    }
    $return['created'] = true;
    $return['id'] = $id_list["_id"]->{'$id'};
} else {
    $return['error'] = "Can't create chat with one person";
}
echo json_encode($return);
?>